import java.net.*;
import java.util.Scanner;
import java.util.concurrent.ConcurrentHashMap;
import java.io.*;

public class ProgramManager {

	private Server mainServer;
	private String nameoffile;
	private int port;
	private int bytesRead, fileSize, current;

	public static ConcurrentHashMap<InetAddress, Connection> activeConnections;

	public ProgramManager(int port) {
		activeConnections = new ConcurrentHashMap<InetAddress, Connection>();
		setNameoffile("name of file");
		this.setPort(port);
		// long start = System.currentTimeMillis();current = 0;

		try {
			setMainServer(new Server(port));
		} catch (IOException e) {}

	}

	public void connectTo(InetAddress ip, int port) {
		Socket socket = null;
		try {
			socket = new Socket(ip, port);
			activeConnections.put(ip, new Connection(socket));
			System.out.println("Connecting...");
			//ask for a specific file assuming the name of the file is known
			Scanner in = new Scanner(System.in);
			PrintWriter writer = new PrintWriter(socket.getOutputStream());
			String nameOfFile = "";
			while (!nameOfFile.matches("n.*")) {
				StringBuilder msg = new StringBuilder();
				System.out.println("Begin message; type ! by itself when done");
				String line = in.nextLine();
				while (!line.equals("!")) {
					msg.append(line);
					msg.append("\n");
					line = in.nextLine();
				}

				writer.print(msg);
				writer.flush();
				System.out.println("waiting for the requested file...");

				// receive  and read the file SUPPOSED TO BE IN A THREAD
				//byte [] mybytearray  = new byte [(int)file.length()];//not to use as we don't know the number of
				byte [] bytesArray   = new byte[fileSize];
				InputStream is = socket.getInputStream();
				System.out.println("receiving the requested file...");
				FileOutputStream fos = new FileOutputStream("the new file");
				BufferedOutputStream bos = new BufferedOutputStream(fos);
				bytesRead = is.read(bytesArray,0,bytesArray.length);
				current = bytesRead;

				do {
					bytesRead =
						is.read(bytesArray, current, (bytesArray.length-current));
					if(bytesRead >= 0) current += bytesRead;
				} while(bytesRead > -1);

				bos.write(bytesArray, 0 , current);
				bos.flush();
				@SuppressWarnings("unused")
				long end = System.currentTimeMillis();
				//System.out.println(end-start);
				bos.close();
				socket.close();
			}
		} catch (IOException e) {}
	}

	public void setMainServer(Server mainServer) {
		this.mainServer = mainServer;
	}

	public Server getMainServer() {
		return mainServer;
	}

	public void setNameoffile(String nameoffile) {
		this.nameoffile = nameoffile;
	}

	public String getNameoffile() {
		return nameoffile;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public int getPort() {
		return port;
	}

	//need a way for to request files from other users and to see incoming requests
	//no idea how to do that
	//have some sort of messaging system?
	//fire events?

}